package istar.behaviour;

import istar.IElement;
import istar.agent.IstarJadeAgent;
import istar.impl.AbstractElement;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public abstract class IstarBehaviour extends Behaviour implements IistarBehaviour{

	private IElement element;
	private boolean error = false;

	public IstarBehaviour (IElement _element){
		super();
		this.element = _element;
		this.setBehaviourName(_element.getName());
	}
	
	@Override
	public void action() {
		try {
			myAction();
		} catch (Exception e) {
			error = true;
			this.element.getMain().getContent().clear();
			//changed here
			this.element.getMain().getContent().add(e.getMessage());
			//((IstarJadeAgent)myAgent).setParameter(element.getExecutionNumber(), element.getName(), e.getMessage());
			
			System.out.println(" >>>>> "+e.getMessage());;
		}
	}
	
	public abstract void myAction() throws Exception;
		
	public abstract int myOnEnd();


	@Override
	public int onEnd() {
		if (error){
			((IstarJadeAgent)myAgent).log("Ending " + this.getBehaviourName() + " with error");
			//System.out.println("Ending " + this.getBehaviourName() + " with error");
			return ERROR_STATE_CODE;
		}
		else
			return myOnEnd();
	}

	public void log(String _phrase){
			((IstarJadeAgent)myAgent).log( _phrase);
	}
	
	public IElement getElement() {
		return element;
	}

	public void setElement(IElement element) {
		this.element = element;
	}

	@Override
	public String getExecutionNumber() {
		return this.element.getExecutionNumber();
	}
	
	
	
}
